<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="账号管理"
      width="680px"
      center
      draggable
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号" prop="username">
              <el-input
                v-model="formValue.username"
                placeholder="账号"
                :disabled="formValue.id != ''"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="昵称" prop="nikename">
              <el-input v-model="formValue.nikename" placeholder="昵称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" v-if="formValue.id == ''">
            <el-form-item label="密码" prop="password">
              <el-input
                type="password"
                v-model="formValue.password"
                placeholder="密码"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formValue.email" placeholder="邮箱"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formValue.phone" placeholder="联系电话"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="accountOrUser == 'accountedit'">
            <el-form-item label="角色" prop="role">
              <el-select-v2
                style="width: 100%"
                v-model="formValue.role"
                :options="rolelist"
                placeholder="请选择角色"
              >
              </el-select-v2>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="formValue.description"
                type="textarea"
                :rows="3"
                placeholder="描述"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" v-if="accountOrUser == 'accountedit'">
            <el-form-item label="状态" prop="enabled">
              <el-switch
                v-model="formValue.enabled"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                inline-prompt
                active-text="启用"
                inactive-text="停用"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="text-align: center" v-has="['account:add', 'account:edit']">
          <el-button
            auto-insert-space
            type="warning"
            @click="updatePasword"
            v-if="formValue.id != '' && accountOrUser == 'accountedit'"
          >
            修改密码
          </el-button>
          <el-button auto-insert-space type="primary" @click="submit(formRef)"> 保存 </el-button>
          <el-button auto-insert-space @click="reset">重置</el-button>
        </div>
      </el-form>
    </el-dialog>

    <update-password ref="updatepassword"></update-password>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules, ElMessage, ElMessageBox } from 'element-plus'
import { usergetById, selectOneByUserName, userSave, userUpdateById } from '@/apis/user.js'
import { selectRolelist } from '@/apis/roles.js'
import UpdatePassword from '@/views/system/account/UpdatePassword.vue'

interface RuleForm {
  id: string
  username: string
  nikename: string
  password: string
  email: string
  role: string
  description: string
  phone: string
  enabled: boolean
}

const formRef = ref<FormInstance>()

let formValue = ref<RuleForm>({
  id: '',
  username: '',
  nikename: '',
  password: '',
  email: '',
  role: null,
  description: '',
  phone: '',
  enabled: true
})

let originValue = {}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,12}$/
    if (!reg.test(value)) {
      callback(new Error('密码必须包含数字、字母，且在6~12位之间'))
    } else {
      callback()
    }
  }
}

const validatePhone = (rule: any, value: any, callback: any) => {
  const reg = /^(((\d{3,4}-)?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/
  if (!reg.test(value)) {
    callback(new Error('联系电话有误请重新输入'))
  } else {
    callback()
  }
}

const validateUsername = (rule: any, value: any, callback: any) => {
  const reg = /^[0-9a-zA-Z_]{3,12}$/
  if (!reg.test(value)) {
    callback(new Error('3~12位由字母、数字、下划线组成'))
  } else {
    selectOneByUserName(value, formValue.value.id)
      .then(function (response) {
        if (response != null) {
          callback(new Error('账号已存在'))
        } else {
          callback()
        }
      })
      .catch(function (error) {
        console.log(error)
      })
  }
}

const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 12, message: '长度在3~12位字符', trigger: 'blur' },
    { validator: validateUsername }
  ],
  nikename: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 8, message: '长度在2~8位字符', trigger: 'blur' }
  ],
  password: [{ required: true, validator: validatePassword }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '输入的邮箱有误', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { validator: validatePhone }
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
})

let dialogVisible = ref(false)

const options = Array.from({ length: 10 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`
}))

let accountOrUser = ref()

function open(id, m) {
  SelectRolelist()

  accountOrUser.value = m

  dialogVisible.value = true

  if (id != undefined && id != null) {
    usergetById({
      id
    })
      .then(function (response) {
        formValue.value = response
        originValue = JSON.parse(JSON.stringify(response))
      })
      .catch(function (error) {
        console.log(error)
      })
  } else {
    let v = {
      id: '',
      username: '',
      nikename: '',
      password: '',
      email: '',
      role: null,
      description: '',
      phone: '',
      enabled: true
    }
    formValue.value = v
    originValue = JSON.parse(JSON.stringify(v))
  }

  reset()
}

function reset() {
  if (!formRef) return
  formRef.value.resetFields()
  formValue.value = JSON.parse(JSON.stringify(originValue))
}

const emit = defineEmits(['getPage'])

function baoCun() {
  ElMessageBox.confirm('确定要保存吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (formValue.value.id == '') {
        userSave(formValue.value)
          .then(function (response) {
            if (response) {
              ElMessage({
                type: 'success',
                message: '保存成功'
              })

              dialogVisible.value = false

              emit('getPage')
            }
          })
          .catch(function (error) {
            console.log(error)
          })
      } else if (formValue.value.id != null) {
        userUpdateById(formValue.value)
          .then(function (response) {
            if (response) {
              ElMessage({
                type: 'success',
                message: '保存成功'
              })

              dialogVisible.value = false
              emit('getPage')
            }
          })
          .catch(function (error) {
            console.log(error)
          })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消保存'
      })
    })
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      baoCun()
    } else {
      console.log('error submit!', fields)
    }
  })
}

let rolelist = ref([])

function SelectRolelist() {
  selectRolelist()
    .then((res) => {
      rolelist.value = []
      res.forEach((element) => {
        rolelist.value.push({ value: element.no, label: element.name })
      })
    })
    .catch((error) => {
      console.log(error)
    })
}

let updatepassword = ref()

function updatePasword() {
  updatepassword.value.open(formValue.value.id)
}

onMounted(() => {})

defineExpose({ open })
</script>

<style lang="scss" scoped></style>
